/* 
Copyright (c) 2004,2005, 2006, 2007, 2008 University of Illinois 

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

3. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
AccessibilityExtension.ns(function() { with (AccessibilityExtension.LIB) {

	var AE = AccessibilityExtension.ns;  
	AE.dialogName = "accessext-form-list-issues";	
	var issuearray = null;

	function issueObjectDisplayDetails() {}
	issueObjectDisplayDetails.prototype = {
		dataElementNames : ['icita07', 'icita08','frequency','msg', 'objclass'],
		columnHeaders : ['column.header.icita07.label', 'column.header.icita08.label','column.header.frequency.label','column.header.msg.label', 'column.header.objclass.label'],
		
		accessIssuesDataElementNames : [],
		accessIssuesMessages : [],
	}
	var issueObjectDisplayDetails = new issueObjectDisplayDetails();
	
	function issueObject(frequency, msgID, objclass, totalObjs) {
		this.frequency = frequency;
		this.icita07 = getErrMsgSeverity(msgID, 'icita07');	
		this.aria = getErrMsgSeverity(msgID, 'aria');	
		this.icita08 = getErrMsgSeverity(msgID, 'icita08');	
		var notApplicable = accessext_getBundleSingleString('msg.unenforced');
		if (frequency == 0) {
			var notApplicable = accessext_getBundleSingleString('msg.unenforced');
			if (this.icita07 != notApplicable)this.icita07 = accessext_getBundleSingleString('msg.pass');
			if (this.aria != notApplicable)this.aria = accessext_getBundleSingleString('msg.pass');
			if (this.icita08 != notApplicable)this.icita08 = accessext_getBundleSingleString('msg.pass');
		}
		this.msgID = msgID
		this.msg = accessext_getBundleSingleString(msgID);
		this.BPLink = getErrMsgBPLink(msgID);
		this.objclass = objclass;
		this.totalObjs = totalObjs;
	}
	issueObject.prototype = {
		frequency : 0,
		icita07 : "",
		aria : "",
		icita08 : "",
		severity : '',
		BPLink : '',
		msgID : '',
		msg : '',
		objclass : '',
		totalObjs : 0,
		details : null,
		display : true,
		displayDetails: issueObjectDisplayDetails,
		getTreeNode : function(windoc) {
			return accesxt_generateTreeboxResults(windoc,this);
		}
	}
AccessibilityExtension.LIB.extend(AccessibilityExtension.LIB,
{
	createIssueObjects: function(ParseFunc, loadArray) {
		try {
			AE.dataarray = new Array();
			ParseFunc(AE.mydoc, AE.dataarray);
			if (AE.dataarray.length > 0) {
				var obj = AE.dataarray[0];
				getIssueFrequency(AE.dataarray); //determine the frequency of each issue
				for (var j = 0; j < obj.displayDetails.accessIssuesDataElementNames.length; j++) {
					var std = currStandard();
					var issueMsg = obj.displayDetails.accessIssuesMessages[j];
				//	if (getErrMsgSeverity(issueMsg, std) != '') {
						var objclass = obj.displayDetails.accessIssuesMessages[j].substring(0, issueMsg.indexOf('.')) + '.title';
						loadArray[loadArray.length] = new issueObject(obj.displayDetails.issueFrequency[j], issueMsg, accessext_getBundleSingleString(objclass), AE.dataarray.length);
						loadArray[loadArray.length-1].details = AE.dataarray;
						if (getErrMsgSeverity(issueMsg, std) == '') {loadArray[loadArray.length-1].display = false;}
					}
				//}
			}	
		} catch (ex) {
			accessext_consoleDump('createIssueObjects exception: ', ex);
		}
	},
	
	InitAccessibilityExt: function() { 
		try {
			AE.sortColumn = "list-header-frequency";
			AE.sortDirectionAscending = true;//use a toggle, so we can just negate
			AE.sortDirection = AE.sortDirectionAscending;
			
			updatePointers();
			accessext_loadDialogPrefs();
			accessext_setNoteCaption();
			if (AE.treebox == null)
				alert(accessext_getBundleString('varisnull',"Treebox"));
			if (AE.mydoc == null)
				alert(accessext_getBundleString('varisnull',"mydoc"));
			if (AE.treebox != null && AE.mydoc != null)
				RefreshList();
		} catch (ex) {
			accessext_consoleDump('InitAccessibilityExt exception: ', ex);
		}
	},
	
	ParseDocument: function(doc) {
		try {
		    window.focus(); 
	
			issuearray = new Array();
			ParseDocumentForIssues(doc, issuearray);
			AE.dataarray = issuearray;	
			RemoveHandler();
		} catch (ex) {
			accessext_consoleDump('ParseDocument exception: ', ex);
		}
	},
	
	ParseDocumentForIssues: function(doc, loadArray) {
		try {
			var documents = accessext_getDocuments(AE.thewindow,new Array());
			var doc = documents[0];
	
			createIssueObjects(ParseDocumentForImageMaps, loadArray); //This will not work if placed after ParseDocumentMenusAndNavigation, why?
			createIssueObjects(ParseDocumentForTitle, loadArray);
			createIssueObjects(ParseDocumentForHeaders, loadArray);
			createIssueObjects(ParseDocumentMenusAndNavigation, loadArray);
	
			createIssueObjects(ParseDocumentForLinks, loadArray);
			createIssueObjects(ParseDocumentForFormElements, loadArray);
			createIssueObjects(ParseDocumentForDataTables, loadArray);
			createIssueObjects(ParseDocumentForLanguages, loadArray);
			createIssueObjects(ParseDocumentForFrames, loadArray);
			createIssueObjects(ParseDocumentForAccessKeys, loadArray); 
				
			createIssueObjects(ParseDocumentForImages, loadArray);
			createIssueObjects(ParseDocumentForObjects, loadArray);		
	//		createIssueObjects(ParseDocumentForAbbreviations, loadArray); do not have accessibility tests
			
			createIssueObjects(ParseDocumentForWidget, loadArray);
			createIssueObjects(ParseDocumentForWidgetRelationships, loadArray);
			createIssueObjects(ParseDocumentForEvents, loadArray);
			
			createIssueObjects(ParseDocumentForColourContrast, loadArray);
		//	createIssueObjects(ParseDocumentForTextFlow, loadArray);   //the resizing is to annoying
			createIssueObjects(ParseDocumentForTextSizing, loadArray);	
			createIssueObjects(ParseDocumentForTextStyling, loadArray);	
			createIssueObjects(ParseDocumentForLayoutTable, loadArray);	
			createIssueObjects(ParseDocumentForLists, loadArray);
			
			createIssueObjects(ParseDocumentForW3Spec, loadArray);
			
		} catch (ex) {
			accessext_consoleDump('ParseDocumentForIssues exception: ', ex);
		}
	},
	
	RemoveHandler: function() {
		var i;
		var currStd = currStandard();
		var notApplicable = accessext_getBundleSingleString('msg.unenforced');
		var elemNA = document.getElementById("checkbox-remove-NA");
		var elemZero = document.getElementById("checkbox-remove-zero");
		for(i = 0; i < AE.dataarray.length; i ++) {
			if(elemNA.checked && AE.dataarray[i][currStd] == notApplicable) { AE.dataarray[i].display = false; }
			else if(elemZero.checked && AE.dataarray[i].frequency == 0) { AE.dataarray[i].display = false; }
			else { AE.dataarray[i].display = true; }
		}
			
		UpdateTreeView();
	},
	
	//toggleSidebar does not work
	toggleSidebarXX: function(){
		try {
			var accessibilityIssuesDialog = window.opener.parent;
			var fireOnThis = accessibilityIssuesDialog.document.getElementById('accessext-toolbarbutton-navigation-title');
		//	var fireOnThis = accessibilityIssuesDialog.document.getElementById('accessext-toolbarbutton-list-dhtml');
		//	var fireOnThis = accessibilityIssuesDialog.document.getElementById('viewAria');
			if (null!= fireOnThis) {
				if( accessibilityIssuesDialog.document.createEvent ) {
				  var evObj = accessibilityIssuesDialog.document.createEvent('MouseEvents');
				  evObj.initEvent( 'onclick', true, false );
			//	  evObj.initEvent( 'oncommand', true, false );
				  fireOnThis.dispatchEvent(evObj);
				} else {
					accessext_consoleDump('createEvent failed ');
				}
			} else {
				accessext_consoleDump('null fireOnThis ');
			}	
		} catch (ex) {
			accessext_consoleDump('toggleSidebar exception: ', ex);
		}
	},
	
	moveTo: function() {
		try {
			var name;
			var theIndex = accessext_getActiveValue(AE.treebox);
			if (theIndex < 0 || theIndex >= AE.dataarray.length  || theIndex == null) {
				return false;
			}
			var objclass = AE.dataarray[theIndex].objclass;
			
		   switch (objclass) {
		      case accessext_getBundleSingleString('accesskey.title'):
		          name = "listofaccesskeys";
		      break;
		      case accessext_getBundleSingleString('links.title'):
		          name = "listoflinks";
		      break;
		      case accessext_getBundleSingleString('headers.title'):
		         name = "listofheaders";
		      break;
		      case accessext_getBundleSingleString('navigation.title'):
		         name = "listofmapelements"; //yes navigation is called map elements
		      break;
		//      case accessext_getBundleSingleString('accesskeys.title'):
		//          name = "listofaccesskeys";
		//      break;
		      case accessext_getBundleSingleString('ariawidget.title'):
			  	name = "listofdhtml";
		        // toggleSidebar('viewAria');
				// return;
		      break;      
		//      case accessext_getBundleSingleString('listofdhtmllog'):
		//         name = "listofdhtmllog";
		//      break;            
		      case accessext_getBundleSingleString('ariarelationships.title'):
			  	name = "listofdhtmlrelationships";
		         //toggleSidebar('viewARIALog');
				 //return;
		      break;            
		//      case accessext_getBundleSingleString('listofdhtmlrdfroles'):
		//         name = "listofdhtmlrdfroles";
		//      break;
		      case accessext_getBundleSingleString('listofmapelements'):
		         name = "listofmapelements";
		      break;
		      case accessext_getBundleSingleString('forms.title'):
		         name = "listofforms";
		      break;
		      case accessext_getBundleSingleString('frames.title'):
		         name = "listofframes";
		      break;
		      case accessext_getBundleSingleString('images.title'):
		          name = "listofimages";
		      break;
		      case accessext_getBundleSingleString('events.title'):
		         name = "listofevents";
		      break;
		//      case 'listofrelations':
		//         name = "listofrelations";
		//      break;
		      case accessext_getBundleSingleString('dataTables.title'):
		          name = "listofdatatables";
		      break;
		      case accessext_getBundleSingleString('titles.title'):
		         name = "title";
		      break;
		      case accessext_getBundleSingleString('colorcontrast.title'):
		         name = "colorcontrast";
		      break;
		      case accessext_getBundleSingleString('w3c.title'):
		          name = "w3cspec";
		      break;
		      case accessext_getBundleSingleString('textflow.title'):
		          name = "textflow";
		      break;
		      case accessext_getBundleSingleString('textsizing.title'):
		          name = "textsizing";
		      break;
		      case accessext_getBundleSingleString('textstyling.title'):
		          name = "textstyling";
		      break;
		      case accessext_getBundleSingleString('layoutTables.title'):
		          name = "contentpositioning";
		      break;
		      case accessext_getBundleSingleString('lists.title'):
		          name = "lists";
		      break;
		//      case accessext_getBundleSingleString('abbr'):
		//         name = "abbr";
		//      break;
		      case accessext_getBundleSingleString('imagemaps.title'):
		        name = "listofimagemaps";
		      break;
		      case accessext_getBundleSingleString('object.title'):
		          name = "listofobjects";
		      break;
		      case accessext_getBundleSingleString('languages.title'):
		           name = "listoflanguage";
		      break;
		     }
			if (name != '') {
				accessext_open_window(name);
			} else {
				accessext_consoleDump('moveTo unknown name: ' + name);
			}
		} catch (ex) {
			accessext_consoleDump('moveTo exception: ', ex);
		}
		
	},
	
	buildErrorSummaryHTML: function(ParseFunc, tableheader) {
		try {
			var retHTML = '';
			
			AE.dataarray = new Array();
			ParseFunc(AE.mydoc, AE.dataarray);
			if (AE.dataarray.length > 0) {
				var objclass = 'undefined class'
				var obj = AE.dataarray[0];
				retHTML += accesxt_generateHTMLTable(objclass, AE.dataarray, tableheader);	
			}else {
				retHTML = retHTML + '<h3>' + tableheader + ' ' + accessext_getBundleSingleString('none') + '</h3>';
			}
			return retHTML;
		} catch (ex) {
			accessext_consoleDump('buildErrorSummaryHTML exception: ', ex);
		}
	},
	
	accessExtDataDumpAsBrowserPage: function(){
		try {
			var outputAll="";
			var documents = accessext_getDocuments(AE.thewindow,new Array());
			var doc = documents[0];
		
			var outputString = "<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en-us' lang='en-us' xmlns:x2='http://www.w3.org/TR/xhtml2'>";
			outputString += "<head><title>Accessibility Extension - " + document.title + " Summary</title></head>";
			outputString += "<body><h1>Accessibility Extension</h1><h2>" + document.title + " Summary</h2>";
			var currentTime = new Date()
			var month = currentTime.getMonth() + 1
			var day = currentTime.getDate()
			var year = currentTime.getFullYear()
			var hours = currentTime.getHours()
			var minutes = currentTime.getMinutes()
			if (minutes < 10) {	minutes = "0" + minutes }
			var strAMPM = "AM";
			if(hours > 11){strAMPM ="PM"}
	
			outputAll += buildErrorSummaryHTML(ParseDocumentForTitle, accessext_getBundleSingleString('titles.title'));
			outputAll += buildErrorSummaryHTML(ParseDocumentForHeaders, accessext_getBundleSingleString('headers.title'));
			outputAll += buildErrorSummaryHTML(ParseDocumentMenusAndNavigation, accessext_getBundleSingleString('navigation.title')); 
			outputAll += buildErrorSummaryHTML(ParseDocumentForImageMaps, accessext_getBundleSingleString('imagemaps.title')); 
			outputAll += buildErrorSummaryHTML(ParseDocumentForLinks,accessext_getBundleSingleString('links.title'));
			outputAll += buildErrorSummaryHTML(ParseDocumentForFormElements, accessext_getBundleSingleString('forms.title'));
			outputAll += buildErrorSummaryHTML(ParseDocumentForDataTables, accessext_getBundleSingleString('datatables.title')); 
			outputAll += buildErrorSummaryHTML(ParseDocumentForLanguages, accessext_getBundleSingleString('languages.title'));
			outputAll += buildErrorSummaryHTML(ParseDocumentForFrames, accessext_getBundleSingleString('frames.title'));
			outputAll += buildErrorSummaryHTML(ParseDocumentForAccessKeys, accessext_getBundleSingleString('accesskeys.title'));
				
			outputAll += buildErrorSummaryHTML(ParseDocumentForImages, accessext_getBundleSingleString('images.title'));
			outputAll += buildErrorSummaryHTML(ParseDocumentForObjects, accessext_getBundleSingleString('object.title'));		
			outputAll += buildErrorSummaryHTML(ParseDocumentForAbbreviations, accessext_getBundleSingleString('abbr.title')); 
			
			outputAll += buildErrorSummaryHTML(ParseDocumentForWidget,accessext_getBundleSingleString('ariawidget.title'));
			outputAll += buildErrorSummaryHTML(ParseDocumentForWidgetRelationships, accessext_getBundleSingleString('ariarelationships.title'));
			outputAll += buildErrorSummaryHTML(ParseDocumentForEvents, accessext_getBundleSingleString('events.title'));
	
			outputAll += buildErrorSummaryHTML(ParseDocumentForColourContrast, accessext_getBundleSingleString('colorcontrast.title'));
			outputAll += buildErrorSummaryHTML(ParseDocumentForTextFlow, accessext_getBundleSingleString('textflow.title'));
			outputAll += buildErrorSummaryHTML(ParseDocumentForTextSizing, accessext_getBundleSingleString('textsizing.title'));
			outputAll += buildErrorSummaryHTML(ParseDocumentForLayoutTable, accessext_getBundleSingleString('layoutTables.title'));
			
			outputAll += buildErrorSummaryHTML(ParseDocumentForW3Spec, accessext_getBundleSingleString('w3c.title'));
			
			
			if (outputAll == "") {
				alert('There is no data to be viewed.')
				return;
			}
			outputString += outputAll + "<br>Date: " + month + "/" + day + "/" + year + " " + hours + ":" + minutes + " " + strAMPM + "<br>";
			outputString += "URL: " + doc.documentURI + "<br>";
			outputString += "</body>";
			
			try {
				var accessibleHTMLPage = window.open("Template.html", "AccessExt as broswer page", 'status=1,toolbar=1,scrollbars=1,menubar=1') 
			} catch (ex) {
				accessext_consoleDump('accessExtAsBrowserPage exception: ' + ex);
			}
		    
			function tryAgain() {
				var bodyElement = accessibleHTMLPage.document.getElementById("bodyID");
		        if (bodyElement) {
		 			bodyElement.innerHTML = outputString;
		        }
		        else {
		             setTimeout (tryAgain, 500);
		        }
			}
		    try {
		 		var bodyElement = accessibleHTMLPage.document.getElementById("bodyID");
				if (!(bodyElement))
		            throw "tantrum";
				else {
		 			bodyElement.innerHTML = outputString;
				}       
		    }
		    catch (ex) {
		        setTimeout (tryAgain, 500);
		        return;
		    }// need to wait until this loads	
		} catch (ex) {
			accessext_consoleDump('accessExtSummaryAsBrowserPage exception: ', ex);
		}
	},
	
	accessext_open_rationale: function() {
		var theIndex = accessext_getActiveValue(AE.treebox);
		if (theIndex < 0 || theIndex >= AE.dataarray.length  || theIndex == null) {
			return false;
		}
	
		//var longdesc = accessext_makeURLAbsolute(node.ownerDocument.location,dataarray[index].BPLink);
		if (AE.dataarray[theIndex].BPLink != '') {
			accessext_generatePage(AE.dataarray[theIndex].BPLink);
		}
		return true;
	},
	
	accessext_issue_select: function() {
		var theIndex = accessext_getActiveValue(AE.treebox);
		if (theIndex < 0 || theIndex >= AE.dataarray.length  || theIndex == null) {
			return false;
		}
		var rationalebutton  = document.getElementById("button-rationale");
		if (rationalebutton == null) {
			return;
		}
	
		try {
			if (AE.dataarray[theIndex].BPLink == '' || AE.dataarray[theIndex].BPLink == null){rationalebutton.disabled = true;}
			else {rationalebutton.disabled = false;}
	
		} catch (ex) {
			accessext_consoleDump('accessext_issue_select exception: ', ex);
		
		}
		
		var accessextNode = AE.mydoc.defaultView.document.getElementById('accessext-callout-img-0');
		for(i = 0; accessextNode != null && i < 1000; i ++) {
			accessextNode = AE.mydoc.defaultView.document.getElementById('accessext-callout-img-' + i);
			if (accessextNode != null) {
				if (accessextNode.parentNode != null){
					accessextNode.parentNode.removeChild(accessextNode);	
				}
			}
		}
	},
	
	RefreshList: function() {
		try {
			updatePointers();
			AE.dataarray = new Array();
		         
			var documents = accessext_getDocuments(AE.thewindow,new Array());
		         
			var progressBar = window.openDialog('chrome://accessext/content/progressbar.xul','progress','resizable=no,centerscreen=yes,alwaysRaised,alwaysRaised=yes');
			AE.mydoc.body.style.cursor = "wait";
			for (var i =0; i < documents.length; i++) {
				ParseDocument(documents[i]);
			}
			AE.mydoc.body.style.cursor = "default";
			progressBar.close();		 
			UpdateTreeView();
		} catch (ex) {
				accessext_consoleDump('RefreshList exception: ', ex);
		}
	},
	 
	InitIssueSummary: function() {
		try {
			AE.sortColumn = "list-header-frequency";
			AE.sortDirectionAscending = true;//use a toggle, so we can just negate
			AE.sortDirection = AE.sortDirectionAscending;
	 
	 		updatePointers();
			accessext_loadDialogPrefs();
			accessext_setNoteCaption();
			if (AE.treebox == null)
				alert(accessext_getBundleString('varisnull',"Treebox"));
			if (AE.mydoc == null)
				alert(accessext_getBundleString('varisnull',"mydoc"));
			if (AE.treebox != null && AE.mydoc != null)
				RefreshList();
		} catch (ex) {
				accessext_consoleDump('InitAccessibilityExt exception: ', ex);
		}
	},
	
	callAccessExtAsBrowserPage: function (){
		AE.primaryarray=undefined; 
		accessExtAsBrowserPage(issuearray);
	}
});
AccessibilityExtension.LIB.InitIssueSummary();	
}});	